package com.example.baselibrary.db.dao;

import com.example.baselibrary.bean.UserManager;
import com.example.baselibrary.db.BTDBHelper;
import com.example.baselibrary.db.table.TopContactsTable;

import java.sql.SQLException;
import java.util.List;
import cc.vv.lklibrary.db.dao.DBBaseTableDao;
import cc.vv.lklibrary.db.help.DBBaseOpenHelper;
import cc.vv.lklibrary.log.LogOperate;

/**
 * 操作常用联系人表的 Dao 类
 *
 * @author Zml
 * @date 2018/3/27.
 */
public class TopContactsDao extends DBBaseTableDao<TopContactsTable, String> {
    /**
     * 常用联系人最多只储存10个
     */
    private static final int MAX_COUNT = 10;

    public TopContactsDao(DBBaseOpenHelper openHelper) {
        super(openHelper);
    }

    private static TopContactsDao mInstance;

    public static TopContactsDao getInstance() {
        if (mInstance == null) {
            synchronized (TopContactsDao.class) {
                if (null == mInstance) {
                    mInstance = new TopContactsDao(BTDBHelper.getInstance());
                }
            }
        }
        return mInstance;
    }

    /**
     * 表中最多保存10条数据,多则删除最早的
     *
     * @param contactsTable
     */
    public void insertOrUpdate(TopContactsTable contactsTable) {
        // 给插入的联系人绑定归属用户
        contactsTable.userId = UserManager.Companion.getUserId();
        // 记录插入时间戳
        contactsTable.timestamp = System.currentTimeMillis();
        // 插入数据更新表
        createOrUpdate(contactsTable);
        // 再查全部
        List<TopContactsTable> topContactsList = queryAll();
        // 判断数量是否超过上限
        if (topContactsList.size() > MAX_COUNT) {
            // 如果超过10个, 移除最后一个
            topContactsList.remove(0);
            // 再清空表
            deleteAll();
            // 然后循环插入数据
            for (TopContactsTable topContactsTable : topContactsList) {
                insert(topContactsTable);
            }
        }
    }

    /**
     * 查询常用联系人 (降序)
     */
    public List<TopContactsTable> queryAllDesc() {
        try {
            return mDao.queryBuilder()
                    // 通过时间戳降序
                    .orderBy("timestamp", false)
                    // 通过 userId 条件查询(只查询当前登录用户的常用联系人)
                    .where().eq("userId",UserManager.Companion.getUserId()).query();
        } catch (SQLException e) {
            LogOperate.e(e);
            e.printStackTrace();
        }
        return null;
    }

}

